<template>
  <div class="payment-container">
    <h1>支付宝支付测试</h1>
    <div class="form-group">
      <label>商品名称</label>
      <input v-model="subject" placeholder="例如：测试商品" />
    </div>
    <div class="form-group">
      <label>支付金额（元）</label>
      <input v-model="totalAmount" placeholder="例如：0.01" />
    </div>
    <button @click="handlePayment" :disabled="loading">
      {{ loading ? '支付中...' : '立即支付' }}
    </button>
  </div>
</template>

<script setup>
import { ref } from 'vue';
// import { useRouter } from 'vue-router';
import axios from 'axios';

// const router = useRouter();
const subject = ref('测试商品');
const totalAmount = ref('0.01');
const loading = ref(false);

const handlePayment = async () => {
  loading.value = true;
  try {
    console.log("Sending payment request...");
    const response = await axios.post(
      'http://localhost:20002/product/api/payment/create',
      `subject=${encodeURIComponent(subject.value)}&totalAmount=${totalAmount.value}`,
      {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
        responseType: 'text'
      }
    );

    console.log("Received response:", response);

    // 调试：检查响应内容
    if (!response.data.includes('punchout_form')) {
      throw new Error('Invalid Alipay response format');
    }

    // 新窗口跳转方案
    const newWindow = window.open('', '_blank');
    newWindow.document.write(response.data);
    newWindow.document.close();
  } catch (error) {
    console.error('Detailed error:', {
      message: error.message,
      response: error.response,
      stack: error.stack
    });
    alert(`支付失败: ${error.message}`);
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped>
.payment-container {
  max-width: 500px;
  margin: 2rem auto;
  padding: 2rem;
  border: 1px solid #eee;
  border-radius: 8px;
}
.form-group {
  margin-bottom: 1rem;
}
.form-group label {
  display: block;
  margin-bottom: 0.5rem;
}
.form-group input {
  width: 100%;
  padding: 0.5rem;
  border: 1px solid #ddd;
  border-radius: 4px;
}
button {
  background-color: #1677ff;
  color: white;
  padding: 0.75rem 1.5rem;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
button:disabled {
  background-color: #ccc;
}
</style>